package com.jacken.mars.commons.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.jacken.mars.commons.enums.SmsPlatform;
import com.jacken.mars.commons.message.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author wq
 * @date 2020-07-09
 */
@Component
@Slf4j
public class AliMessageManager {

    private final SmsConfig smsConfig;

    public AliMessageManager(SmsConfig smsConfig) {
        this.smsConfig = smsConfig;
    }

    /**
     * 发送短信
     *
     * @param smsPlatform  短信平台 admin  app
     * @param phone        电话号码
     * @param code         验证码
     * @param templateCode 发送模板
     * @return 是否发送成功
     */
    public boolean sendSms(String smsPlatform, String phone, String code, String templateCode) {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        DefaultProfile profile = DefaultProfile.getProfile("default", smsConfig.getAliAppKey(), smsConfig.getAliAppSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "default");
        request.putQueryParameter("PhoneNumbers", phone);
        if (smsPlatform.equals(SmsPlatform.APP.getCode())) {
            request.putQueryParameter("SignName", "脸咔");
        } else {
            request.putQueryParameter("SignName", "脸咔后台管理系统");
        }
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject jsonObject = JSON.parseObject(response.getData());
            log.info("----sms-----response-----" + response.getData());
            if (jsonObject.get("Code").equals("OK")) {
                return true;
            }
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
